package com.dpstudio.ymprestlful.view.console;

import com.dpstudio.ymprestlful.beans.HttpMethod;
import com.dpstudio.ymprestlful.beans.Request;
import com.dpstudio.ymprestlful.utils.RestUtil;
import com.dpstudio.ymprestlful.view.window.frame.RestDetail;
import com.dpstudio.ymprestlful.view.window.frame.RightToolWindow;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.ui.Messages;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.cert.ocsp.Req;
import org.jetbrains.annotations.NotNull;

import java.util.*;

public class ConsoleAction extends AnAction {
    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        String selectText = Objects.requireNonNull(e.getData(CommonDataKeys.CARET)).getSelectedText();
        if (StringUtils.isBlank(selectText)) {
            Messages.showInfoMessage("请选择正确的路径！", "警告!");
            return;
        }
        if (!selectText.contains(":")) {
            Messages.showInfoMessage("请选择带请求方法的文本！", "警告!");
            return;
        }
        if (selectText.endsWith(":")) {
            selectText = selectText.substring(0, selectText.length() - 1);
        }
        boolean errorShow = true;
        for (String value : HttpMethod.valueList()) {
            if (selectText.contains(value.toUpperCase())) {
                errorShow = false;
            }
        }
        if (errorShow) {
            Messages.showInfoMessage("请选择带请求方法的文本！", "警告!");
            return;
        }

        Map<String, List<Request>> allRequest = RestUtil.getAllRequest(e.getProject());
        allRequest.forEach((moduleName, requests) -> requests.removeIf(next -> !RightToolWindow.METHOD_CHOOSE_MAP.get(next.getMethod())));
        List<Request> requestList = new ArrayList<>();
        allRequest.forEach((k, v) -> requestList.addAll(v));

        String[] selectTextArray = selectText.split(":");
        if (selectTextArray.length != 2) {
            Messages.showInfoMessage("请选择带请求方法的文本！", "警告!");
            return;
        }
        String methodName = StringUtils.trim(selectTextArray[0]);
        String url = StringUtils.trim(selectTextArray[1]);
        Request request = new Request(HttpMethod.valueOf(methodName.toUpperCase(Locale.ROOT)), url);
        for (Request re : requestList) {
          if(re.getMethod()==request.getMethod() && re.getPath().equals(request.getPath())){
              re.getPsiMethod().navigate(true);
              break;
          }
        }
    }
}
